import { getCurrentInstance, onMounted, ref } from 'vue'
import { time } from '@/utils/moment'

import { useCode } from '@/hooks/code'
import {
  createArticleAPI,
  updateArticleAPI,
  articleAPI,
  changeArticleStateAPI,
  deleteArticleAPI,
  gainArticleAPI,
} from '@/api'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import type { ArticleData } from '@/utils/interface'

const userStore = useUserStore()

const { tackleCode } = useCode()

export function useArticle() {
  const router = useRouter()
  const proxy: any = getCurrentInstance()?.proxy

  // 文章id
  const id = ref<number>()

  // 获取form内容
  const form = ref()
  const formData = (data: any) => {
    form.value = data
  }
  // 接收editor内容
  const editor = ref()
  const editorData = (data: any) => {
    console.log('editorData', data)

    editor.value = data
  }

  // 收取cover封面
  const cover = ref()
  const coverData = (data: any) => {
    console.log('coverData', data)
    cover.value = data
  }

  // 发布
  const nowMoment = ref()
  const submit = async (e: number) => {
    if (e === 0) {
      const nowTime = new Date()
      nowMoment.value = time(nowTime)
    }
    if (form.value && form.value.title && !id.value) {
      const value = {
        ...form.value,
        ...{
          content: editor.value,
          state: e,
          moment: new Date(),
        },
      }
      if (cover.value) {
        value.cover = cover.value
      }
      const request = {
        token: userStore.token,
        value,
      }
      const res: any = await createArticleAPI(request)
      if (tackleCode(res.code)) {
        if (e === 0) {
          id.value = res.data
          proxy.$message({
            type: 'primary',
            message: '文章已保存',
          })
        } else if (e === 1) {
          proxy.$message({
            type: 'primary',
            message: '文章已发布',
          })
          router.push('/overview')
        }
      }
    } else if (id.value) {
      // 存在id说明已经保存过，更新
      const value = {
        ...form.value,
        ...{
          content: editor.value,
          state: e,
        },
      }
      if (cover.value) {
        value.cover = cover.value
      }
      const request = {
        token: userStore.token,
        value,
        id: id.value,
      }
      const res: any = await updateArticleAPI(request)
      if (tackleCode(res.code)) {
        if (e === 0) {
          proxy.$message({
            type: 'primary',
            message: '文章已保存',
          })
        } else if (e === 1) {
          proxy.$message({
            type: 'primary',
            message: '文章已发布',
          })
          router.push('/overview')
        }
      }
    } else {
      proxy.$message({
        type: 'warning',
        message: '请输入文章标题',
      })
    }
  }

  // 获取文章
  // 文章
  const articleList = ref<ArticleData[]>([])

  // 文章总数
  const count = ref<number>(0)

  const getData = async (req: any) => {
    const res: any = await articleAPI(req)
    if (tackleCode(res.code)) {
      if (req.count) {
        count.value = res.data.count
      }
      articleList.value = [...res.data.result]
    }
  }

  // 修改文章发布状态
  const updateState = async (e: { id: number; state: number }) => {
    const request = {
      token: userStore.token,
      articleId: e.id,
      state: e.state,
    }
    const res: any = await changeArticleStateAPI(request)
    if (tackleCode(res.code)) {
      console.log(res)
      articleList.value.filter((i: { id: number; state: number }) => {
        if (i.id === e.id) {
          i.state = e.state
          if (e.state === 1) {
            proxy.$message({ type: 'primary', message: '发布成功' })
          } else {
            proxy.$message({ type: 'primary', message: '已撤回' })
          }
        }
      })
    }
  }

  // 删除文章
  const deleteArticle = async (id: number) => {
    const request = {
      token: userStore.token,
      articleId: id,
    }
    const res: any = await deleteArticleAPI(request)
    if (tackleCode(res.code)) {
      console.log(res)
      articleList.value = articleList.value.filter((item) => item.id !== id)
      proxy.$message({ type: 'primary', message: '删除成功' })
    }
  }

  // 获取文章详情
  const defaultArticle = ref()
  const getArticleDet = async () => {
    const request = {
      token: userStore.token,
      articleId: id.value,
    }
    const res: any = await gainArticleAPI(request)
    if (tackleCode(res.code)) {
      const content = res.data.content
      const cover = res.data.cover
      const formData = res.data
      delete formData.id
      delete formData.views
      delete formData.moment
      delete formData.content
      delete formData.state
      if (formData.label) {
        formData.label = formData.label.split(',')
      }
      defaultArticle.value = { content, formData, cover }
    }
  }
  onMounted(() => {
    if (id.value) {
      getArticleDet()
    }
  })

  return {
    formData,
    editorData,
    nowMoment,
    submit,
    getData,
    articleList,
    count,
    updateState,
    deleteArticle,
    id,
    defaultArticle,
    coverData,
  }
}
